package com.xzy.rabbit.demo.workqueue.g;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.xzy.rabbit.common.util.RabbitUtil;
import com.xzy.rabbit.demo.workqueue.Producer;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeoutException;

/**
 * 工作模式（Work Queue）
 *
 * @author xzy
 * @date 2021年9月23日
 */
public class Main {
    private static final Integer MESSAGE_COUNT = 10;
    private static final String QUEUE_NAME = "work_queue_g";

    /**
     * 手动应答 + 预取值
     */
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1.创建连接
        ConnectionFactory connectionFactory = RabbitUtil.CONNECTION_FACTORY;
        Connection connection = connectionFactory.newConnection();

        // 2.生产消息（发布任务）
        CountDownLatch countDownLatch = new CountDownLatch(MESSAGE_COUNT);
        Thread produceThread = new Thread(new Producer(connection, QUEUE_NAME, MESSAGE_COUNT, 100L), "PRODUCE");
        produceThread.start();

        // 2.消费消息（工作线程）
        Thread workThread1 = new Thread(new Consumer(connection, QUEUE_NAME, countDownLatch, 7, 1000L), "CONSUME1");
        Thread workThread2 = new Thread(new Consumer(connection, QUEUE_NAME, countDownLatch, 1, 10L), "CONSUME2");
        workThread1.start();
        workThread2.start();

        countDownLatch.await();
        connection.close();

        /*
         * 从代码执行结果可以看出，设置“预取值”不保证工作线程一定能够拿到那么多消息，“预取值”低但工作效率高的工作线程拿到的消息可能比“预取值”高但效率低的工作线程多。
         */
    }
}
